//
//  HomeViewController.m
//  陶瓷
//
//  Created by 郭天龙 on 15/6/6.
//  Copyright (c) 2015年 王戈. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeScrollHeaderView.h"
#import "HomeHeadTableViewCell.h"
#import "TCNetworkTool.h"
#import "HomeAdvertiseModel.h"
#import "HomeCategoryModel.h"
#import "HomeNomalCellTableViewCell.h"
#import "HomeCellModel.h"
#import "HomeADInfoViewController.h"
#import "TCSearchViewController.h"
#import "CompanyDisplayViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface HomeViewController ()<UITableViewDataSource,UITableViewDelegate,HomeScrollHeaderViewDelegate,HomeHeadTableViewCellDelegate,HomeNomalCellTableViewCellDelegate,CLLocationManagerDelegate>

@property (nonatomic, weak) IBOutlet UITableView *tableview;

@property (nonatomic, weak) IBOutlet UILabel *cityLabel;
@property (nonatomic, strong) HomeAdvertiseModel *model;
@property (nonatomic, strong) NSMutableArray *arrayDataSource;

@property (nonatomic, retain) CLLocationManager* locationMgr;
@property (nonatomic, retain) CLGeocoder* clGeocoder;
@property (weak, nonatomic) IBOutlet UIView *searchView;

@end

@implementation HomeViewController

-(IBAction)clickCateButton:(id)sender
{
    NSDictionary *userinfo = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"index", nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotification_ChangeTab object:nil userInfo:userinfo];
}

- (IBAction)clickSearchButton:(id)sender
{
    TCSearchViewController *searchVC = [[TCSearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
}

#pragma mark - HomeNomalCellTableViewCellDelegate
- (void)didADInfoVC:(NSDictionary *)model
{
    TCNetworkTool *tctool = [TCNetworkTool sharedNetTool];
    [tctool GetCompanyWithID:[model objectForKey:@"TargetId"] andSuccessBlocks:^(NSArray *resultArray) {
        CompanyDisplayViewController *nextController = [[CompanyDisplayViewController alloc] init];
        nextController.company = resultArray.firstObject;
        //        self.navigationItem.leftBarButtonItem.title = @"";
        self.title = @"";
        [self.navigationController pushViewController:nextController animated:YES];
    } andFailureBlocks:^(NSString *failureMessage) {
        [MBHUDHelper showWarningWithText:failureMessage];
    }];
}

#pragma mark - HomeHeaderViewDelegate
- (void)didAdvertiseButton:(id)dic
{
    TCNetworkTool *tctool = [TCNetworkTool sharedNetTool];
    [tctool GetCompanyWithID:[NSString stringWithFormat:@"%@",[dic objectForKey:@"TargetId"]] andSuccessBlocks:^(NSArray *resultArray) {
        CompanyDisplayViewController *nextController = [[CompanyDisplayViewController alloc] init];
        self.title = @"";
        nextController.company = resultArray.firstObject;
        [self.navigationController pushViewController:nextController animated:YES];
    } andFailureBlocks:^(NSString *failureMessage) {
        [MBHUDHelper showWarningWithText:failureMessage];
    }];
    
    
}

#pragma mark - HomeHeadTableViewCellDelegate
- (void)didCategoryButton:(id)dic
{
    NSDictionary *userinfo = [NSDictionary dictionaryWithObjectsAndKeys:[dic objectForKey:@"TargetId"],@"cate",@"1",@"index", nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotification_ChangeTab object:nil userInfo:userinfo];
}

- (void)didDiscoverButton:(id)dic
{
    NSDictionary *userinfo = [NSDictionary dictionaryWithObjectsAndKeys:(NSString *)dic,@"disc",@"2",@"index", nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotification_ChangeTab object:nil userInfo:userinfo];
}

- (void)didTailButton:(id)dic
{
    NSDictionary *userinfo = [NSDictionary dictionaryWithObjectsAndKeys:(NSString *)dic,@"tail",@"3",@"index", nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotification_ChangeTab object:nil userInfo:userinfo];
}


#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    else
    {
        return [self.arrayDataSource count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        HomeHeadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"homeCellId"];
        if (!cell) {
            cell = [[NSBundle mainBundle] loadNibNamed:@"HomeHeadTableViewCell" owner:nil options:nil].firstObject;
            [cell setDelegate:self];
            [cell setArray:self.model.middelModelArray];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
        }
        return cell;
    }
    else
    {
        HomeNomalCellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"homeCellId"];
        if (!cell) {
            cell = [[NSBundle mainBundle] loadNibNamed:@"HomeNomalCellTableViewCell" owner:nil options:nil].firstObject;
            [cell setModelWithDic:[self.arrayDataSource objectAtIndex:indexPath.row]];
            cell.delegate = self;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        return cell;
    }
}

#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 140;
    }
    else
    {
        NSDictionary *dic = [self.arrayDataSource objectAtIndex:indexPath.row];
        return [[dic objectForKey:@"Height"] floatValue]/2;
    }
}

- (void)setupNavigationBar
{
    self.navigationController.navigationBarHidden = YES;
}


#pragma mark - lifecycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableview.hidden = YES;
    _tableview.bounces = NO;
    self.model = [[HomeAdvertiseModel alloc] init];
    [self setupNavigationBar];
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.locationMgr = [[CLLocationManager alloc] init];
    
    //设置代理
    self.locationMgr.delegate = self;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) {
        //[_locationManager requestWhenInUseAuthorization];//⓵只在前台开启定位
        [self.locationMgr requestAlwaysAuthorization];//⓶在后台也可定位
    }
    // 5.iOS9新特性：将允许出现这种场景：同一app中多个location manager：一些只能在前台定位，另一些可在后台定位（并可随时禁止其后台定位）。
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
        self.locationMgr.allowsBackgroundLocationUpdates = YES;
    }
    
    // 设置定位精度
    // kCLLocationAccuracyNearestTenMeters:精度10米
    // kCLLocationAccuracyHundredMeters:精度100 米
    // kCLLocationAccuracyKilometer:精度1000 米
    // kCLLocationAccuracyThreeKilometers:精度3000米
    // kCLLocationAccuracyBest:设备使用电池供电时候最高的精度
    // kCLLocationAccuracyBestForNavigation:导航情况下最高精度，一般要有外接电源时才能使用
    self.locationMgr.desiredAccuracy = kCLLocationAccuracyBest;
    
    // distanceFilter是距离过滤器，为了减少对定位装置的轮询次数，位置的改变不会每次都去通知委托，而是在移动了足够的距离时才通知委托程序
    // 它的单位是米，这里设置为至少移动1000再通知委托处理更新;
    self.locationMgr.distanceFilter = 1000.0f;
    
    //开始定位
    [self.locationMgr startUpdatingLocation];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}

- (void)refreshTableView
{
    [SVProgressHUD showWithStatus:@"正在更新数据 请稍后.."];
    
    TCBaseTool *base =[TCBaseTool sharedBaseTool];
    [base NetCityIdFromPositionlatitiyde:base.locaLatitude longitude:base.locaLongitude SuccessBlock:^{
        if (![base.currentCityName isEqualToString:@""] && base.currentCityName) {
            self.cityLabel.text = base.currentCityName;
        }
        TCNetworkTool *net = [TCNetworkTool sharedNetTool];
        [net getHomeAdvertiseSuccessBlocks:^(NSDictionary *resultDic) {
            [SVProgressHUD dismiss];
            self.tableview.hidden = NO;
            self.model.headerModelArray = [NSArray arrayWithArray:[resultDic objectForKey:@"Top"] ];
            self.model.middelModelArray = [NSArray arrayWithArray:[resultDic objectForKey:@"Middle"] ];
            self.arrayDataSource = [resultDic objectForKey:@"Bottom"];
            [self setupHeaderView];
            [self.tableview reloadData];
            _tableview.contentSize = CGSizeMake(_tableview.contentSize.width, _tableview.contentSize.height -40);
            
        } andFailureBlocks:^(NSString *failureMessage) {
            self.tableview.hidden = NO;
            [self setupHeaderView];
            [self.tableview reloadData];
            [SVProgressHUD dismiss];
            //        [MBHUDHelper showWarningWithText:failureMessage];
        }];
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - LocationDelegate
// iso 6.0以上SDK版本使用，包括6.0。
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *cl = [locations objectAtIndex:0];
    TCBaseTool *base =[TCBaseTool sharedBaseTool];
    base.locaLatitude = cl.coordinate.latitude;
    base.locaLongitude = cl.coordinate.longitude;
    [self refreshTableView];
}


// 获取定位失败回调方法
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"Location error!");
}

- (void)setupHeaderView
{
    if (self.model.headerModelArray.count != 0) {
        HomeScrollHeaderView *headview = [[HomeScrollHeaderView alloc] initWithFrame:CGRectMake(0, 0, kDefaultWindowWidth, kDefaultWindowWidth*31/72 + 64)];
        headview.delegate = self;
        headview.images =  self.model.headerModelArray;
        headview.scrollTime = 3.0f;
        [headview loadLoopScrollView];
        self.tableview.tableHeaderView = headview;
    }
    else
    {
        UIView *empty = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kDefaultWindowWidth, kDefaultWindowHeight)];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(kDefaultWindowWidth*0.5-150, kDefaultWindowHeight*0.5-50, 300, 50)];
        label.text = @"您所在的城市没有信息";
        label.textAlignment = NSTextAlignmentCenter;
        [empty addSubview:label];
        self.tableview.tableHeaderView = empty;
    }
    if ([self.tableview respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableview setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    if ([self.tableview respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableview setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

- (void)setupFirstSectionView
{
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat alphaRate = _tableview.contentOffset.y / 162.0;
    
    _searchView.backgroundColor = TCColor(59, 158, 207, alphaRate);
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
